<template>
  <div class="multi-checkout">
    <h2>结算购物车</h2>
    <el-card>
      <!-- 菜品信息 -->
      <div class="dish-info">
        <h3>菜品信息</h3>
        <el-table :data="selectedDishes" border style="width: 100%">
          <el-table-column label="菜品名称" align="center" prop="name" />
          <el-table-column label="菜品图片" align="center">
            <template #default="{ row }">
              <el-image
                  style="width: 100px; height: 100px"
                  :src="row.imageUrl"
                  fit="cover"
              />
            </template>
          </el-table-column>
          <el-table-column label="单价" align="center">
            <template #default="{ row }">
              ¥ {{ row.price.toFixed(2) }}
            </template>
          </el-table-column>
          <el-table-column label="数量" align="center">
            <template #default="{ row }">
              <el-input-number
                  v-model="row.quantity"
                  :min="1"
                  @change="updateQuantity(row)"
              />
            </template>
          </el-table-column>
          <el-table-column label="总价" align="center">
            <template #default="{ row }">
              ¥ {{ (row.price * row.quantity).toFixed(2) }}
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 配送地址 -->
      <div class="address-info">
        <h3>选择配送地址</h3>
        <!-- 没有地址时的提示 -->
        <div v-if="addresses.length === 0" class="no-address">
          <p>您还没有添加收货地址，请先添加地址。</p>
          <el-button type="primary" @click="goToAddressPage">添加收货地址</el-button>
        </div>

        <!-- 有地址时的选择框 -->
        <el-select
            v-else
            v-model="selectedAddressId"
            placeholder="请选择配送地址"
            class="address-select"
        >
          <el-option
              v-for="address in addresses"
              :key="address.addressId"
              :label="formatAddressLabel(address)"
              :value="address.addressId"
          />
        </el-select>

        <!-- 选中地址的详细信息 -->
        <div v-if="selectedAddressId" class="selected-address-details">
          <p><span class="label">收货人姓名：</span>{{ selectedAddress?.username }}</p>
          <p><span class="label">收货人手机号：</span>{{ selectedAddress?.phone }}</p>
          <p><span class="label">收货地址：</span>{{ selectedAddress?.addressDetail }}</p>
        </div>
      </div>

      <!-- 总金额 -->
      <div class="total-price">
        <h3>总金额</h3>
        <p><span class="label">总价：</span>¥ {{ totalPrice.toFixed(2) }}</p>
      </div>

      <!-- 立即支付按钮 -->
      <div class="actions">
        <el-button type="primary" @click="handlePay">立即支付</el-button>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { apiGet, apiPost } from '@/utils/api';
import { useUserStore } from '@/store/modules/user';
import type { Address, Dish } from '@/types/entity';
import { sessionStorage } from '@/utils/storage';

const router = useRouter();
const userStore = useUserStore();

// 从购物车页面传递的选中菜品
const selectedDishes = ref<Array<{ dishId: number; name: string; price: number; quantity: number; imageUrl: string }>>(
    JSON.parse(sessionStorage.get('selectedDishes') || '[]')
);

// 检查是否有选中的菜品
if (selectedDishes.value.length === 0) {
  ElMessage.error('未选中任何菜品');
  router.push('/cart'); // 跳转回购物车页面
}

// 配送地址列表
const addresses = ref<Address[]>([]);
const selectedAddressId = ref<number | null>(null);

// 当前选中的地址
const selectedAddress = computed(() => {
  return addresses.value.find(addr => addr.addressId === selectedAddressId.value);
});

// 计算总金额
const totalPrice = computed(() => {
  return selectedDishes.value.reduce((total, dish) => {
    return total + dish.price * dish.quantity;
  }, 0);
});

// 获取用户配送地址
const fetchUserAddresses = async () => {
  const { data } = await apiGet('/address/getAllByUserId', { userId: userStore.id });
  addresses.value = data;

  // 默认选择默认地址
  const defaultAddress = data.find((addr: Address) => addr.isDefault === 1);
  if (defaultAddress) {
    selectedAddressId.value = defaultAddress.addressId;
  } else if (data.length > 0) {
    selectedAddressId.value = data[0].addressId; // 如果没有默认地址，选择第一个地址
  }
};

// 跳转到收货地址管理页面
const goToAddressPage = () => {
  router.push('/user/address');
};

// 处理立即支付
const handlePay = async () => {
  if (!selectedAddressId.value) {
    ElMessage.warning('请选择配送地址');
    return;
  }

  // 构造订单数据
  const orderDTO = {
    userId: userStore.id,
    addressId: selectedAddressId.value,
    paymentMethod: 1, // 假设支付方式为支付宝
    orderStatus: 1, // 订单状态为待支付
    items: selectedDishes.value.map(dish => ({
      dishId: dish.dishId,
      quantity: dish.quantity,
      price: dish.price,
      totalPrice: dish.price * dish.quantity,
    })),
  };

  // 调用后端接口，生成支付订单
  const response = await fetch(`${import.meta.env.VITE_SERVE}alipay/pay-multi`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      token: sessionStorage.get('token') || '', // 传递 token
    },
    body: JSON.stringify(orderDTO),
  });

  if (response.ok) {
    // 获取返回的 HTML 表单
    const formHtml = await response.text();

    // 将表单插入到页面中并自动提交
    const div = document.createElement('div');
    div.innerHTML = formHtml;
    document.body.appendChild(div);
    document.forms[0].submit(); // 自动提交表单
  } else {
    ElMessage.error('支付失败');
  }
};

// 格式化地址显示
const formatAddressLabel = (address: Address) => {
  return `${address.username} | ${address.phone} | ${address.addressDetail}`;
};

// 更新菜品数量
const updateQuantity = (dish: { dishId: number; quantity: number }) => {
  // 更新购物车中的数量
  const index = selectedDishes.value.findIndex(item => item.dishId === dish.dishId);
  if (index !== -1) {
    selectedDishes.value[index].quantity = dish.quantity;
  }
};

// 初始化时获取数据
onMounted(() => {
  fetchUserAddresses();
});
</script>

<style scoped>
.multi-checkout {
  max-width: 800px;
  margin: 20px auto;
  padding: 20px;
}

.dish-info {
  margin-bottom: 20px;
}

.label {
  font-weight: bold;
  color: #333;
}

.address-info {
  margin-bottom: 20px;
}

.no-address {
  text-align: center;
  padding: 20px;
  background-color: #f9f9f9;
  border-radius: 8px;
}

.no-address p {
  margin-bottom: 10px;
  color: #666;
}

.address-select {
  width: 100%;
  margin-bottom: 20px;
}

.selected-address-details {
  margin-top: 10px;
  padding: 10px;
  background-color: #f9f9f9;
  border-radius: 8px;
}

.total-price {
  margin-bottom: 20px;
}

.total-price h3 {
  font-size: 18px;
  font-weight: bold;
}

.total-price p {
  font-size: 24px;
  color: #f56c6c;
  font-weight: bold;
}

.actions {
  text-align: right;
}
</style>